Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
jsx-ast-utils
Advanced tools
The jsx-ast-utils package provides utilities for working with the Abstract Syntax Tree (AST) of JSX elements. It is commonly used in the development of linting rules and tools that analyze or transform JSX code.
Element and attribute extraction
This feature allows you to extract properties and their literal values from a JSX element. It is useful when analyzing components for specific attribute values.
const { getProp, getLiteralPropValue } = require('jsx-ast-utils');
const JSXElement = ...; // some JSX element AST node
const prop = getProp(JSXElement, 'href');
const value = getLiteralPropValue(prop);
Event handler detection
This feature helps in detecting event handlers on JSX elements. It can be used to ensure that interactive elements have appropriate event handlers for accessibility.
const { getProp, elementType } = require('jsx-ast-utils');
const JSXElement = ...; // some JSX element AST node
const type = elementType(JSXElement);
const onClickProp = getProp(JSXElement, 'onClick');
const isButtonWithOnClick = type === 'button' && onClickProp !== undefined;
Checking for children
These utilities allow you to check if a JSX element has any children or if every child meets a specific condition. This can be used to enforce content structure within components.
const { hasAnyChildren, hasEveryChild } = require('jsx-ast-utils');
const JSXElement = ...; // some JSX element AST node
const hasChildren = hasAnyChildren(JSXElement);
const hasSpecificChildren = hasEveryChild(JSXElement, child => child.type === 'JSXText');
This package is a Babel plugin that allows for transformation of JSX syntax. It provides similar AST manipulation capabilities but is more focused on compiling JSX to JavaScript rather than analyzing or linting.
This package includes a collection of ESLint rules for React and JSX. It uses AST analysis to enforce best practices and coding standards. While it does not provide low-level AST utilities like jsx-ast-utils, it serves a similar purpose in the context of linting and code quality.
react-docgen is a CLI and toolkit for extracting information from React component files for documentation generation. It analyzes the AST to gather prop types, default values, and component descriptions. It is similar in that it analyzes JSX, but it is more specialized for documentation purposes.
[![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url]
[![npm badge][npm-badge-png]][package-url]
AST utility module for statically analyzing JSX.
$ npm i jsx-ast-utils --save
This is a utility module to evaluate AST objects for JSX syntax. This can be super useful when writing linting rules for JSX code. It was originally in the code for eslint-plugin-jsx-a11y, however I thought it could be useful to be extracted and maintained separately so you could write new interesting rules to statically analyze JSX.
import { hasProp } from 'jsx-ast-utils';
// OR: var hasProp = require('jsx-ast-utils').hasProp;
// OR: const hasProp = require('jsx-ast-utils/hasProp');
// OR: import hasProp from 'jsx-ast-utils/hasProp';
module.exports = context => ({
JSXOpeningElement: node => {
const onChange = hasProp(node.attributes, 'onChange');
if (onChange) {
context.report({
node,
message: `No onChange!`
});
}
}
});
hasProp(props, prop, options);
Returns boolean indicating whether an prop exists as an attribute on a JSX element node.
Object - The attributes on the visited node. (Usually node.attributes
).
String - A string representation of the prop you want to check for existence.
Object - An object representing options for existence checking
ignoreCase
- automatically set to true
.spreadStrict
- automatically set to true
. This means if spread operator exists in
props, it will assume the prop you are looking for is not in the spread.
Example: <div {...props} />
looking for specific prop here will return false if spreadStrict
is true
.hasAnyProp(props, prop, options);
Returns a boolean indicating if any of props in prop
argument exist on the node.
Object - The attributes on the visited node. (Usually node.attributes
).
Array - An array of strings representing the props you want to check for existence.
Object - An object representing options for existence checking
ignoreCase
- automatically set to true
.spreadStrict
- automatically set to true
. This means if spread operator exists in
props, it will assume the prop you are looking for is not in the spread.
Example: <div {...props} />
looking for specific prop here will return false if spreadStrict
is true
.hasEveryProp(props, prop, options);
Returns a boolean indicating if all of props in prop
argument exist on the node.
Object - The attributes on the visited node. (Usually node.attributes
).
Array - An array of strings representing the props you want to check for existence.
Object - An object representing options for existence checking
ignoreCase
- automatically set to true
.spreadStrict
- automatically set to true
. This means if spread operator exists in
props, it will assume the prop you are looking for is not in the spread.
Example: <div {...props} />
looking for specific prop here will return false if spreadStrict
is true
.getProp(props, prop, options);
Returns the JSXAttribute itself or undefined, indicating the prop is not present on the JSXOpeningElement.
Object - The attributes on the visited node. (Usually node.attributes
).
String - A string representation of the prop you want to check for existence.
Object - An object representing options for existence checking
ignoreCase
- automatically set to true
.elementType(node)
Returns the tagName associated with a JSXElement.
Object - The visited JSXElement node object.
getPropValue(prop);
Returns the value of a given attribute. Different types of attributes have their associated values in different properties on the object.
This function should return the most closely associated value with the intention of the JSX.
Object - The JSXAttribute collected by AST parser.
getLiteralPropValue(prop);
Returns the value of a given attribute. Different types of attributes have their associated values in different properties on the object.
This function should return a value only if we can extract a literal value from its attribute (i.e. values that have generic types in JavaScript - strings, numbers, booleans, etc.)
Object - The JSXAttribute collected by AST parser.
propName(prop);
Returns the name associated with a JSXAttribute. For example, given <div foo="bar" />
and the JSXAttribute for foo
, this will return the string "foo"
.
Object - The JSXAttribute collected by AST parser.
console.log(eventHandlers);
/*
[
'onCopy',
'onCut',
'onPaste',
'onCompositionEnd',
'onCompositionStart',
'onCompositionUpdate',
'onKeyDown',
'onKeyPress',
'onKeyUp',
'onFocus',
'onBlur',
'onChange',
'onInput',
'onSubmit',
'onClick',
'onContextMenu',
'onDblClick',
'onDoubleClick',
'onDrag',
'onDragEnd',
'onDragEnter',
'onDragExit',
'onDragLeave',
'onDragOver',
'onDragStart',
'onDrop',
'onMouseDown',
'onMouseEnter',
'onMouseLeave',
'onMouseMove',
'onMouseOut',
'onMouseOver',
'onMouseUp',
'onSelect',
'onTouchCancel',
'onTouchEnd',
'onTouchMove',
'onTouchStart',
'onScroll',
'onWheel',
'onAbort',
'onCanPlay',
'onCanPlayThrough',
'onDurationChange',
'onEmptied',
'onEncrypted',
'onEnded',
'onError',
'onLoadedData',
'onLoadedMetadata',
'onLoadStart',
'onPause',
'onPlay',
'onPlaying',
'onProgress',
'onRateChange',
'onSeeked',
'onSeeking',
'onStalled',
'onSuspend',
'onTimeUpdate',
'onVolumeChange',
'onWaiting',
'onLoad',
'onError',
'onAnimationStart',
'onAnimationEnd',
'onAnimationIteration',
'onTransitionEnd',
]
*/
Contains a flat list of common event handler props used in JSX to attach behaviors to DOM events.
The same list as eventHandlers
, grouped into types.
console.log(eventHandlersByType);
/*
{
clipboard: [ 'onCopy', 'onCut', 'onPaste' ],
composition: [ 'onCompositionEnd', 'onCompositionStart', 'onCompositionUpdate' ],
keyboard: [ 'onKeyDown', 'onKeyPress', 'onKeyUp' ],
focus: [ 'onFocus', 'onBlur' ],
form: [ 'onChange', 'onInput', 'onSubmit' ],
mouse: [ 'onClick', 'onContextMenu', 'onDblClick', 'onDoubleClick', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragExit', 'onDragLeave', 'onDragOver', 'onDragStart', 'onDrop', 'onMouseDown', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseOut', 'onMouseOver', 'onMouseUp' ],
selection: [ 'onSelect' ],
touch: [ 'onTouchCancel', 'onTouchEnd', 'onTouchMove', 'onTouchStart' ],
ui: [ 'onScroll' ],
wheel: [ 'onWheel' ],
media: [ 'onAbort', 'onCanPlay', 'onCanPlayThrough', 'onDurationChange', 'onEmptied', 'onEncrypted', 'onEnded', 'onError', 'onLoadedData', 'onLoadedMetadata', 'onLoadStart', 'onPause', 'onPlay', 'onPlaying', 'onProgress', 'onRateChange', 'onSeeked', 'onSeeking', 'onStalled', 'onSuspend', 'onTimeUpdate', 'onVolumeChange', 'onWaiting' ],
image: [ 'onLoad', 'onError' ],
animation: [ 'onAnimationStart', 'onAnimationEnd', 'onAnimationIteration' ],
transition: [ 'onTransitionEnd' ],
}
*/
FAQs
AST utility module for statically analyzing JSX
The npm package jsx-ast-utils receives a total of 8,524,798 weekly downloads. As such, jsx-ast-utils popularity was classified as popular.
We found that jsx-ast-utils demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.